<?php
require_once("../data/db_connection.php");
require_once("../Utils.php");

	$db = new db();
	$user_id = $_GET['user_id'];
	$exist_friend_arr = array();
	// 从联系人中查出还未被邀请的好友
	$sql1 = "SELECT pFriendId FROM pTableRelation WHERE pUserId = " . $user_id;
	$sql2 = "SELECT friend_id FROM contacts WHERE user_id = " . $user_id . " and friend_id NOT IN ( " . $user_id . ", ";
	if ($result = $db->query($sql1)) {
		while($row = $result->fetch_assoc()) {
			$sql2 .= $row['pFriendId'] . ', ';
		}
		$len = strlen($sql2);
		$sql2 = substr($sql2, 0, $len-2);
		$sql2 .= ")";
		echo 'sql2 = ' . $sql2 . '<br />';
	}
?>
<html>
<head>
模拟-好友邀请-向通讯录中的好友发出邀请 
</head>
<body>
<h1>填入id，点击submit，就能向ta发出邀请了</h1>
<form id="form1" name="add_contact_form" method="post" action="">
<input type="text" name="user_id" value="<?php echo $_GET['user_id'];?>"/>
选择想要邀请的朋友：<br />
	<?php 
	
	if ($result = $db->query($sql2)) {
		while($row = $result->fetch_assoc()) {
			//echo "<option value='" . $row['_id'] . "'>" . $row['_id'] . "</option>";
			echo "<input type='checkbox' name='friends[]' value='" . $row['friend_id'] . "'/>" . $row['friend_id'] . '<br />';
		}
	}
	?>
<input type="submit" name="Submit" value="邀请" /> 
</form>
<?php
	$contacts = $_POST['friends'];
	$contacts_count = sizeof($contacts);
	$success_count = 0;
	foreach($contacts as $elem) {
		// 0 = 双方确认 1 = userid发出方未确认 2  = friend接受方，未确认
		// 与数据库匹配
		$sql3 = "INSERT INTO pTableRelation VALUES ( NULL, " . $user_id . ", ". $elem . ", 1)";
		$return_id = $db->insert_get_id($sql3);
		if ($return_id > 0) {
			$success_count++;
		}
		$sql3 = "INSERT INTO pTableRelation VALUES ( NULL, " . $elem . ", " . $user_id . ", 2)";
		$return_id = $db->insert_get_id($sql3);
		if ($return_id > 0) {
			$success_count++;
		}
	}
	if ($contacts_count ) {
		if ($success_count == 2 * $contacts_count) { 
			echo '发送邀请成功' . "<br />";
		} else {
			echo '发送邀请失败！';
		}
	}

?>
</body>
</html>